package mbsl.storage;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;

import mbsl.system.Logger;

public class DatabaseClient {
	private static Logger logger = new Logger(DatabaseClient.class);
	
	public static void main(String[] pArgs) {
		new DatabaseClient();
	}
	
	private Statement mStatement;
	private JTable mTable;
	@SuppressWarnings("serial")
	public DatabaseClient() {
		try {
			System.out.print("Loading Driver............");
			Class.forName("org.hsqldb.jdbcDriver");
			System.out.println("Done");
			
			System.out.print("Establishing Connection...");
			mStatement = DriverManager.getConnection("jdbc:hsqldb:file:mbsldb", "sa", "").createStatement();
			System.out.println("Done");
		} catch (ClassNotFoundException e) {
			System.out.println("Failed");
			logger.fatal("Could not find database driver.");
			return;
		} catch (SQLException e) {
			System.out.println("Failed");
			logger.fatal("Could not open database connection.", e);
			return;
		}
		
		JFrame frame = new JFrame("MBSL Database Client") {
			@Override
			public void dispose() {
				close();
			}
		};
		final JTextField input = new JTextField();
		mTable = new JTable(getMessage("ready", ""));
		
		frame.setBounds(0, 0, 400, 400);
		frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		input.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				update(input.getText());
			}
		});
		input.setPreferredSize(new Dimension(input.getWidth(), 20));
		
		frame.add(input, BorderLayout.NORTH);
		frame.add(new JScrollPane(mTable), BorderLayout.CENTER);
		
		frame.setVisible(true);
	}
	
	private void update(String pCommand) {
		try {
			boolean isRS = mStatement.execute(pCommand);
			
			if (pCommand.equals("shutdown"))
				close();

			if (isRS) {
				ResultSet rs = mStatement.getResultSet();
				
				DefaultTableModel m = new DefaultTableModel();
				
				for (int i = 1; i <= rs.getMetaData().getColumnCount(); i++)
					m.addColumn(rs.getMetaData().getColumnName(i));
				
				while (rs.next()) {
					String[] row = new String[rs.getMetaData().getColumnCount()];
					
					for (int i = 1; i <= row.length; i++)
						row[i - 1] = rs.getString(i);
					
					m.addRow(row);
				}
				
				mTable.setModel(m);
			} else
				mTable.setModel(getMessage(mStatement.getUpdateCount(), "Result"));
		} catch (SQLException e) {
			mTable.setModel(getMessage(e.getMessage(), "Error"));
			e.printStackTrace();
		}
	}
	
	private DefaultTableModel getMessage(Object pMessage, String pHeader) {
		return new DefaultTableModel(new Object[][] {{pMessage}}, new Object[]{pHeader});
	}
	
	private void close() {
		System.exit(0);
	}
}
